package com.cqgcxy.shopping.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Properties;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;

/**
 * 生成验证码
 * @author cqyhm
 *
 */
@WebServlet(urlPatterns= {"/kaptcha.png"})
public class KaptchaServlet extends HttpServlet {

	
	
	private static final long serialVersionUID = 1841583091386826158L;
	private Logger logger=LoggerFactory.getLogger(getClass());
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//设置验证码的属性
		Properties prop=new Properties();
		
		prop.put("kaptcha.textproducer.char.length", "4");
		
		DefaultKaptcha producer=new DefaultKaptcha();
		producer.setConfig(new Config(prop));
		logger.debug("执行验证码pang");
		//生成随机文本
		String str=producer.createText();
		logger.info("生成的验证码：{}",str);
		HttpSession session=req.getSession();
		session.setAttribute("kaptcha", str);
		//生成图像
		BufferedImage image=producer.createImage(str);
		//设置输出类型
		resp.setContentType("image/png");
		//输出图片流
		ImageIO.write(image, "png", resp.getOutputStream());
	}
}
